import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import ElementPlus, {ElMessage} from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import axios from 'axios'

// 配置axios
axios.defaults.baseURL = 'http://localhost:8080/api'
axios.defaults.timeout = 10000

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 从localStorage中获取token
    const token = localStorage.getItem('token')
    const tokenHead = localStorage.getItem('tokenHead')
    if (token && tokenHead) {
      // 将token添加到请求头
      config.headers['Authorization'] = tokenHead + token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response && error.response.status === 401) {
      // 清除token
      localStorage.removeItem('token')
      localStorage.removeItem('tokenHead')
      localStorage.removeItem('expireTime')
      localStorage.removeItem('userInfo')

      // 重定向到登录页
      router.push('/login')
    } else {
        ElMessage.error(error.message);
    }
    // return Promise.reject(error)
  }
)

const app = createApp(App)

// 注册ElementPlus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(router)
app.use(ElementPlus)
app.config.globalProperties.$axios = axios

app.mount('#app')


